package com.ala4.oxcafe.boot.manager;

import com.ala4.oxcafe.boot.enums.UserTypeEnum;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author PING
 * @version 1.0
 * @date 2024/12/20 16:25
 */
@Data
@Accessors(chain = true)
@JsonIgnoreProperties(value = {"password", "authorities"})
public class CustomUserDetails implements UserDetails {

    public CustomUserDetails() {
        this.issuedAt = Instant.now();
    }


    public CustomUserDetails(User user) {
        this();
        this.userId = 0L;
        this.userAccount = user.getUsername();
        this.nickName = user.getUsername();
        this.password = user.getPassword();
    }

    private Long userId;
    private String userAccount;
    private String password;
    private String nickName;
    private UserTypeEnum userType;
    private String avatar;
    /**
     * 手机号码
     */
    private String phone;
    /**
     * 用户状态
     */
    private Integer status;
    /**
     * 用户token
     */
    private String token;
    /**
     * 用户失效时间
     */
    private Instant expiresAt;
    /**
     * 用户登录时间
     */
    private Instant issuedAt;

    /**
     * 用户角色
     */
    private List<String> roles = List.of();

    /**
     * 是否门店用户(0是 1否)
     */
    private Integer isStoreUser;

    /**
     * 门店ID-如果有门店ID就会带门店ID查询业务数据
     */
    private Long storeId;

    @Override
    public Collection<UserGrantedAuthority> getAuthorities() {
        return roles.stream().map(item -> "ROLE_" + item).map(UserGrantedAuthority::new).toList();
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.userAccount;
    }

    @Override
    public boolean isEnabled() {
        // 0是正常 1停用
        return Objects.equals(status, 0);
    }

}
